package com.example.permission.service.impl;

import com.example.permission.entity.*;
import com.example.permission.repository.*;
import com.example.permission.service.UserPermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@RequiredArgsConstructor
public class UserPermissionServiceImpl implements UserPermissionService {

    private final UserRoleRepository userRoleRepository;
    private final RoleApiPermissionRepository roleApiPermissionRepository;
    private final RoleMenuRepository roleMenuRepository;
    private final MenuRepository menuRepository;
    private final ApiResourceRepository apiResourceRepository;

    @Override
    public boolean hasPermission(Long uid, String apiCode, String requiredPermissionType) {
        List<UserRole> roles = userRoleRepository.findByUserId(uid);
        Optional<ApiResource> resourceOpt = apiResourceRepository.findByCode(apiCode);
        if (!resourceOpt.isPresent()) return false;

        Long apiId = resourceOpt.get().getId();
        for (UserRole role : roles) {
            List<RoleApiPermission> perms = roleApiPermissionRepository.findByRoleId(role.getRoleId());
            for (RoleApiPermission perm : perms) {
                if (Objects.equals(perm.getApiId(), apiId) &&
                    (perm.getPermissionType().equals(requiredPermissionType) || perm.getPermissionType().equals("ALL"))) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public List<Menu> getUserMenus(Long uid) {
        List<UserRole> roles = userRoleRepository.findByUserId(uid);
        Set<Long> menuIds = new HashSet<>();
        for (UserRole role : roles) {
            List<RoleMenu> roleMenus = roleMenuRepository.findByRoleId(role.getRoleId());
            roleMenus.forEach(rm -> menuIds.add(rm.getMenuId()));
        }
        return menuRepository.findAllById(menuIds);
    }
}

